﻿/**
 * IMonAIR: A new open-source library for instant messenger connectivity. <http://code.google.com/p/imonair/>
 *
 * This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 */
/**
 * @author Andre de Groot <http://www.cmd.tech.nhl.nl/users/groot406/weblog/>
 * @author Piotr Zema <http://felixz.mark-naegeli.com>
 */
package {
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import net.imonair.msn.connectors.MSNConnector;
	import net.imonair.msn.contacts.MSNContact;
	import net.imonair.msn.contacts.MSNStatus;
	import net.imonair.msn.chats.MSNMessage;
	import net.imonair.msn.events.MSNConnectorEvent;
	import net.imonair.msn.events.MSNChatEvent;
	import net.imonair.msn.events.MSNContactListEvent;
	
	public class IMonAIR_blank extends Sprite {
		
		private const LIVE_ID:String = "imonair@hotmail.com";
		private const PASSWORD:String = "*&obelix";
		
		private var msn:MSNConnector;
		
		public function IMonAIR_blank() {
			msn = new MSNConnector(LIVE_ID, PASSWORD);
			msn.addEventListener(MSNConnectorEvent.CONNECT, msnConnected);
			msn.addEventListener(MSNConnectorEvent.SIGN_IN, msnLoggedIn);
			msn.debug = false;
		}
		private function msnConnected(event:Event):void {//If the connetor is connected you are ready to login, needs to be called each time.
			msn.signIn(LIVE_ID, PASSWORD);
		}
		private function msnLoggedIn(event:MSNConnectorEvent):void {//If you're loggedIn, you can get your contact list
			event.currentTarget.removeEventListener(MSNConnectorEvent.SIGN_IN, msnLoggedIn);
			
			msn.addEventListener(MSNContactListEvent.SYNCED, contactListSynced);
			msn.syncContactList();
		}
		private function contactListSynced(event:MSNContactListEvent):void {

			//If you're contact list is synced  (or just loaded in this case), you can perform actions on the account
			var contactList:Array = event.target.contacts;

			//Like setting your status
			this.msn.status = MSNStatus.ONLINE;
			
			//Or sending messages (to Andre de Groot's account in this case)
			/*
			var contact:MSNContact = contactList[0];

			this.msn.sendMessage(contact, 'test message 1');
			this.msn.sendMessage(contact, 'test message 2');
			*/
			
			
			//Or changing your name
			this.msn.displayName = "IMonAIR Project account || see: http://code.google.com/p/imonair";

			//Or adding a new contact
			// this.msn.addContact("friendsEmail@hotmail.com");
			
			//Another good thing is to listen for incomming messages
			this.msn.addEventListener(MSNChatEvent.MESSAGE_RECEIVED, messageReceived);
		}
		private function messageReceived(event:MSNChatEvent):void {
			var message:MSNMessage = event.message as MSNMessage;
			trace(message.sender.displayName + " says: " + message.message);
		}
	}
}
/*
	import nl.acht.connectors.msn.MSNConnector;
	import nl.acht.connectors.msn.MSNContact;
	import nl.acht.events.MSNEvent;
	
	import MSNChatWindow;
	
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.*;
	import fl.controls.*;
	import fl.data.DataProvider;
	import flash.data.EncryptedLocalStore;
	import flash.utils.ByteArray;
	
	import flash.display.NativeWindowInitOptions;
	import flash.display.NativeWindowSystemChrome;
	import flash.display.NativeWindowType;
	import flash.display.NativeWindow;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.geom.Rectangle;
		
	public class MSNClient_AIR extends Sprite
	{
		private var msn		:MSNConnector;
		private var dp		:DataProvider;			
		private var randInt	:uint
		private var score	:Object = new Object();
		
		private var confersations:Array = new Array();
		private var openChats:Array = new Array();
		
		private var loginWindow:NativeWindow;
		
		public function MSNClient_AIR()
		{
			createLoginWindow();
					
			msn = new MSNConnector();
			msn.addEventListener(Event.CONNECT, connected)
			
			initStatusChanger();
			configureListeners();
		}
		
		private function createLoginWindow()
		{
			var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
			windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD;
			windowOptions.type = NativeWindowType.UTILITY;
			windowOptions.resizable = false;

			loginWindow = new NativeWindow(windowOptions);
			loginWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
			loginWindow.stage.align = StageAlign.TOP_LEFT;
			loginWindow.bounds = new Rectangle(100, 100, 225, 150);
			loginWindow.stage.addChild(login_window);
			loginWindow.addEventListener(Event.DEACTIVATE, function() { loginWindow.activate() } );
		}
		
		private function connected(e:Event)
		{
			if(login_window.email_inp.text == '' && login_window.password_inp.text == '')
			{
				if(EncryptedLocalStore.getItem("email"))
				{
					var storedEmail:ByteArray = EncryptedLocalStore.getItem("email");
					login_window.email_inp.text = storedEmail.readUTFBytes(storedEmail.length);
					EncryptedLocalStore.removeItem("email");
				}
				
				if(EncryptedLocalStore.getItem("password"))
				{
					var storedPassword:ByteArray = EncryptedLocalStore.getItem("password");
					login_window.password_inp.text = storedPassword.readUTFBytes(storedPassword.length);
					EncryptedLocalStore.removeItem("password");
				}
				
				if(EncryptedLocalStore.getItem("rememberstate"))
				{
					var storedRememberState:ByteArray = EncryptedLocalStore.getItem("rememberstate");
					login_window.remember.selected = storedRememberState.readBoolean();
					EncryptedLocalStore.removeItem("rememberstate");
				}
				
				loginWindow.activate();
				login_window.email_inp.setFocus();
				login_window.signin_btn.addEventListener(MouseEvent.CLICK, loginClickHandler);
			} else {
				msn.connect(login_window.email_inp.text, login_window.password_inp.text);
				login_window.email_inp.text = '';
				login_window.password_inp.text = '';
			}
		}
		
		private function loginClickHandler(evt:MouseEvent)
		{
			if(login_window.remember.selected == true)
			{
				var email:String = login_window.email_inp.text;
				var emailBytes:ByteArray = new ByteArray();
				emailBytes.writeUTFBytes(email);
				EncryptedLocalStore.setItem("email", emailBytes);
				
				var pass:String = login_window.password_inp.text;
				var passBytes:ByteArray = new ByteArray();
				passBytes.writeUTFBytes(pass);
				EncryptedLocalStore.setItem("password", passBytes);
				
				var rememberState:Boolean = login_window.remember.selected;
				var rememberBytes:ByteArray = new ByteArray();
				rememberBytes.writeBoolean(rememberState);
				EncryptedLocalStore.setItem("rememberstate", rememberBytes);

			}
			
			loginWindow.close();
			msn.connect(login_window.email_inp.text, login_window.password_inp.text);
		}
		
		private function initStatusChanger()
		{
			statusChanger.addItem({label:"Online",		value:MSNConnector.ONLINE});
			statusChanger.addItem({label:"Away", 			value:MSNConnector.AWAY});
			statusChanger.addItem({label:"Busy", 			value:MSNConnector.BUSY});
			statusChanger.addItem({label:"Be Right Back", value:MSNConnector.BE_RIGHT_BACK});
			statusChanger.addItem({label:"Telephone", 	value:MSNConnector.PHONE});
			statusChanger.addItem({label:"Out to Lunch", 	value:MSNConnector.LUNCH});
			statusChanger.addItem({label:"Idle", 			value:MSNConnector.IDLE});
			statusChanger.addItem({label:"Hidden", 		value:MSNConnector.HIDDEN});
			statusChanger.rowCount = statusChanger.length;
		}
		
		private function configureListeners()
		{
			msn.addEventListener(MSNEvent.CONNECT, 						loggedIn);
			msn.addEventListener(MSNEvent.CONTACTS_READY, 				contactListSynched);
			msn.addEventListener(MSNEvent.CONTACT_ONLINE,				newContactOnline);
			msn.addEventListener(MSNEvent.ADDED_BY_CONTACT, 			newFriendInvitationHandler);
			msn.addEventListener(MSNEvent.CONTACT_ADDED, 				newContactHandler);
			msn.addEventListener(MSNEvent.CONTACT_REMOVED,				removedContactHandler);
			msn.addEventListener(MSNEvent.CONTACT_CHANGE, 				contactListUpdateHandler);
			msn.addEventListener(MSNEvent.MESSAGE_RECEIVED, 			messageReceivedHandler);
			msn.addEventListener(MSNEvent.GROUP_CONVERSATION_STARTED, 	groupSessionsChanged);
			msn.addEventListener(MSNEvent.GROUP_CONVERSATION_CLOSED, 	groupSessionsChanged);
			msn.addEventListener(MSNEvent.GROUP_CONTACT_JOINED, 		groupSessionsChanged);
			msn.addEventListener(MSNEvent.GROUP_CONTACT_REMOVED, 		groupSessionsChanged);

			removeContactBTN.addEventListener(	MouseEvent.CLICK, removeContactHandler);
			addBTN.addEventListener(			MouseEvent.CLICK, addContact);
			blockContactBTN.addEventListener(	MouseEvent.CLICK, blockContact);
			unBlockContactBTN.addEventListener(	MouseEvent.CLICK, unBlockContact);
			changeNameBTN.addEventListener(		MouseEvent.CLICK, changeName);
		}
		
		private function loggedIn(e:MSNEvent)
		{
			statusChanger.addEventListener(Event.CHANGE, changeStatus);

			nameInput.text = e.data.nickname;
			
			dp = new DataProvider();
		
			contacts_dg.addColumn('nickname');
			contacts_dg.dataProvider = dp;
			
			msn.syncContactList();
		}
		
		private function contactListSynched(e:MSNEvent)
		{
			msn.setStatus(MSNConnector.AWAY);
			dp = new DataProvider();
		
			contacts_dg.dataProvider = dp;
			dp.addItems(msn.getOnlineContacts().sortOn('nickname'));
			contacts_dg.addEventListener(MouseEvent.DOUBLE_CLICK, openChat);
		}
		
		private function openChat(e:*)
		{		
			var chatWindow:MSNChatWindow;
			if(!this.openChats[this.contacts_dg.selectedItem.email])
			{
				chatWindow = new MSNChatWindow(msn, this.contacts_dg.selectedItem);
				this.openChats[this.contacts_dg.selectedItem.email] = chatWindow;
			} else
				chatWindow = this.openChats[this.contacts_dg.selectedItem.email];
						
			chatWindow.activate();
		}
		
		private function newContactOnline(e:MSNEvent)
		{
			//this.dp.addItem(e.data)
		}
		
		private function newFriendInvitationHandler(e:MSNEvent)
		{
			//trace('got invitation');
		}
		
		private function newContactHandler(e:MSNEvent)
		{
			//trace('friend added to contactlist');
		}
		
		private function removeContactHandler(e:MouseEvent)
		{
			msn.removeContact(this.contacts_dg.selectedItem.email, false)
		}
		
		private function removedContactHandler(e:MSNEvent)
		{
			refreshContactList();
		}
		
		private function refreshContactList()
		{
			if(this.contacts_dg.selectedItem)
				var oldSelectedEmail:String = this.contacts_dg.selectedItem.email;
			this.dp.removeAll();
			this.dp.addItems(msn.getOnlineContacts().sortOn('nickname'));
			
			addGroupSessions();
			
			if(oldSelectedEmail)
				for(var i:uint = 0; i<this.dp.length; i++)
					if(this.dp.getItemAt(i).email == oldSelectedEmail)
						this.contacts_dg.selectedIndex = i
		}
		
		private function addContact(e:MouseEvent)
		{
			msn.addContact(contactInput.text);
		}
		
		private function blockContact(e:MouseEvent)
		{
			msn.blockContact(this.contacts_dg.selectedItem.email)
		}
		
		private function unBlockContact(e:MouseEvent)
		{
			msn.unBlockContact(this.contacts_dg.selectedItem.email)
		}
		
		private function contactListUpdateHandler(e:MSNEvent)
		{
			refreshContactList();
		}
		
		private function changeStatus(e:Event)
		{
			msn.setStatus(e.target.selectedItem.value);
		}
		
		private function groupSessionsChanged(e:MSNEvent)
		{
			refreshContactList();
		}
		
		private function addGroupSessions()
		{
			for(var i:uint = 0; i < msn.getGroupSessions().length; i++)
			{
				var groupNames:Array = new Array();
				
				for(var j:uint = 0; j < msn.getGroupSessions()[i].contacts.length; j++)
					groupNames.push(msn.getGroupSessions()[i].contacts[j].nickname);
				
				var listObj:Object 	= new Object();
				listObj.nickname 	= groupNames.join(", ");
				listObj.switchBoard	= msn.getGroupSessions()[i];
				listObj.email		= 'group_'+[i];
				this.dp.addItem(listObj);
			}
		}
		
		private function changeName(e:MouseEvent)
		{
			msn.setName(this.nameInput.text);
		}
						
		private function selectContact(msg:Object)
		{
			for(var i:uint = 0; i < this.contacts_dg.length; i++)
			{
				if(msg.switchBoard == this.contacts_dg.getItemAt(i).switchBoard)
					this.contacts_dg.selectedIndex = i;
			}
		}
		
		private function messageReceivedHandler(e:MSNEvent)
		{
			var message:Object = e.data;
			
			var chatOpen:Boolean = false;
			var chatWindow:MSNChatWindow;
			
			for(var i:String in openChats)
			{
				if(this.openChats[i].getSwitchBoard() == message.switchBoard)
				{
					chatWindow = this.openChats[i];
					chatOpen = true;
					break;
				}
			}
			
			if(chatOpen == false)
			{
				chatWindow = new MSNChatWindow(msn, message.fromContact);
				chatWindow.activate();
				this.openChats[message.fromContact.email] = chatWindow;
			}
			
			chatWindow.notify();
			chatWindow.msgReceived(message);
		}
		
	}
}

*/